package spiner

import (
	"fmt"
	"strings"
)

type Spinner struct {
	chars string
	max   int
	cur   int
	pf    func(s string, args ...interface{})
}

func New(pf func(s string, args ...interface{})) *Spinner {
	chars := `-\|/`
	return &Spinner{chars: chars, max: len(chars), pf: pf}
}

func (p *Spinner) Printf(prefix string, s string, args ...interface{}) {
	p.cur++
	p.pf("\r%s[%c]%s", prefix, p.chars[p.cur%p.max], fmt.Sprintf(strings.TrimSpace(s), args...))
}

func (p *Spinner) PrintProgress(percent int, prefix, format string) {
	if format == "" {
		format = " %d%%"
	}
	if percent != p.cur {
		p.cur++
		p.pf("\r%s[%c]%s", prefix, p.chars[p.cur%p.max], fmt.Sprintf(format, percent))
		if percent == 100 {
			p.pf("\n")
		}
	}
}

func (p *Spinner) Clean(s string, args ...interface{}) {
	s = "\r" + s + "%s\n"
	p.pf(s, append(args, strings.Repeat(" ", 80-len(s)))...)
}
